import { useState } from 'react'
import './Forms.css'

// 基本受控组件
function BasicControlledExample() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    age: '',
    gender: '',
    hobbies: []
  })

  const handleInputChange = (e) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  const handleHobbyChange = (hobby) => {
    setFormData(prev => ({
      ...prev,
      hobbies: prev.hobbies.includes(hobby)
        ? prev.hobbies.filter(h => h !== hobby)
        : [...prev.hobbies, hobby]
    }))
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    alert(`表单数据: ${JSON.stringify(formData, null, 2)}`)
  }

  const handleReset = () => {
    setFormData({
      name: '',
      email: '',
      age: '',
      gender: '',
      hobbies: []
    })
  }

  return (
    <div className="example-container">
      <h4>基本受控组件</h4>
      
      <form onSubmit={handleSubmit} className="form">
        <div className="form-group">
          <label>姓名:</label>
          <input
            type="text"
            name="name"
            value={formData.name}
            onChange={handleInputChange}
            placeholder="请输入姓名"
          />
        </div>

        <div className="form-group">
          <label>邮箱:</label>
          <input
            type="email"
            name="email"
            value={formData.email}
            onChange={handleInputChange}
            placeholder="请输入邮箱"
          />
        </div>

        <div className="form-group">
          <label>年龄:</label>
          <input
            type="number"
            name="age"
            value={formData.age}
            onChange={handleInputChange}
            min="1"
            max="120"
          />
        </div>

        <div className="form-group">
          <label>性别:</label>
          <div className="radio-group">
            <label>
              <input
                type="radio"
                name="gender"
                value="male"
                checked={formData.gender === 'male'}
                onChange={handleInputChange}
              />
              男
            </label>
            <label>
              <input
                type="radio"
                name="gender"
                value="female"
                checked={formData.gender === 'female'}
                onChange={handleInputChange}
              />
              女
            </label>
            <label>
              <input
                type="radio"
                name="gender"
                value="other"
                checked={formData.gender === 'other'}
                onChange={handleInputChange}
              />
              其他
            </label>
          </div>
        </div>

        <div className="form-group">
          <label>爱好:</label>
          <div className="checkbox-group">
            {['阅读', '运动', '音乐', '旅行', '编程'].map(hobby => (
              <label key={hobby}>
                <input
                  type="checkbox"
                  checked={formData.hobbies.includes(hobby)}
                  onChange={() => handleHobbyChange(hobby)}
                />
                {hobby}
              </label>
            ))}
          </div>
        </div>

        <div className="form-actions">
          <button type="submit" className="submit-btn">提交</button>
          <button type="button" onClick={handleReset} className="reset-btn">重置</button>
        </div>
      </form>

      <div className="form-preview">
        <h5>当前表单数据:</h5>
        <pre>{JSON.stringify(formData, null, 2)}</pre>
      </div>
    </div>
  )
}

// 文本域和下拉选择
function TextareaSelectExample() {
  const [formData, setFormData] = useState({
    description: '',
    city: '',
    experience: '',
    skills: []
  })

  const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都']
  const experiences = ['应届生', '1-3年', '3-5年', '5-10年', '10年以上']
  const allSkills = ['JavaScript', 'React', 'Vue', 'Angular', 'Node.js', 'Python', 'Java']

  const handleInputChange = (e) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  const handleSkillChange = (e) => {
    const selectedOptions = Array.from(e.target.selectedOptions, option => option.value)
    setFormData(prev => ({
      ...prev,
      skills: selectedOptions
    }))
  }

  return (
    <div className="example-container">
      <h4>文本域和下拉选择</h4>
      
      <form className="form">
        <div className="form-group">
          <label>个人描述:</label>
          <textarea
            name="description"
            value={formData.description}
            onChange={handleInputChange}
            rows="4"
            placeholder="请描述您的个人情况..."
          />
        </div>

        <div className="form-group">
          <label>期望城市:</label>
          <select
            name="city"
            value={formData.city}
            onChange={handleInputChange}
          >
            <option value="">请选择城市</option>
            {cities.map(city => (
              <option key={city} value={city}>{city}</option>
            ))}
          </select>
        </div>

        <div className="form-group">
          <label>工作经验:</label>
          <select
            name="experience"
            value={formData.experience}
            onChange={handleInputChange}
          >
            <option value="">请选择经验</option>
            {experiences.map(exp => (
              <option key={exp} value={exp}>{exp}</option>
            ))}
          </select>
        </div>

        <div className="form-group">
          <label>技能 (多选):</label>
          <select
            multiple
            value={formData.skills}
            onChange={handleSkillChange}
            size="5"
          >
            {allSkills.map(skill => (
              <option key={skill} value={skill}>{skill}</option>
            ))}
          </select>
        </div>
      </form>

      <div className="form-preview">
        <h5>当前表单数据:</h5>
        <pre>{JSON.stringify(formData, null, 2)}</pre>
      </div>
    </div>
  )
}

// 表单验证
function ValidationExample() {
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    confirmPassword: '',
    email: '',
    phone: ''
  })

  const [errors, setErrors] = useState({})

  const validateForm = () => {
    const newErrors = {}

    // 用户名验证
    if (!formData.username.trim()) {
      newErrors.username = '用户名不能为空'
    } else if (formData.username.length < 3) {
      newErrors.username = '用户名至少3个字符'
    } else if (formData.username.length > 20) {
      newErrors.username = '用户名不能超过20个字符'
    }

    // 密码验证
    if (!formData.password) {
      newErrors.password = '密码不能为空'
    } else if (formData.password.length < 6) {
      newErrors.password = '密码至少6个字符'
    }

    // 确认密码验证
    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = '两次密码输入不一致'
    }

    // 邮箱验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!formData.email.trim()) {
      newErrors.email = '邮箱不能为空'
    } else if (!emailRegex.test(formData.email)) {
      newErrors.email = '邮箱格式不正确'
    }

    // 手机号验证
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!formData.phone.trim()) {
      newErrors.phone = '手机号不能为空'
    } else if (!phoneRegex.test(formData.phone)) {
      newErrors.phone = '手机号格式不正确'
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleInputChange = (e) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
    
    // 清除对应字段的错误
    if (errors[name]) {
      setErrors(prev => {
        const newErrors = { ...prev }
        delete newErrors[name]
        return newErrors
      })
    }
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    
    if (validateForm()) {
      alert('表单验证通过，提交成功!')
      console.log('提交的数据:', formData)
    } else {
      alert('表单验证失败，请检查输入')
    }
  }

  return (
    <div className="example-container">
      <h4>表单验证</h4>
      
      <form onSubmit={handleSubmit} className="form validation-form">
        <div className="form-group">
          <label>用户名:</label>
          <input
            type="text"
            name="username"
            value={formData.username}
            onChange={handleInputChange}
            className={errors.username ? 'error' : ''}
            placeholder="3-20个字符"
          />
          {errors.username && <span className="error-message">{errors.username}</span>}
        </div>

        <div className="form-group">
          <label>密码:</label>
          <input
            type="password"
            name="password"
            value={formData.password}
            onChange={handleInputChange}
            className={errors.password ? 'error' : ''}
            placeholder="至少6个字符"
          />
          {errors.password && <span className="error-message">{errors.password}</span>}
        </div>

        <div className="form-group">
          <label>确认密码:</label>
          <input
            type="password"
            name="confirmPassword"
            value={formData.confirmPassword}
            onChange={handleInputChange}
            className={errors.confirmPassword ? 'error' : ''}
            placeholder="再次输入密码"
          />
          {errors.confirmPassword && <span className="error-message">{errors.confirmPassword}</span>}
        </div>

        <div className="form-group">
          <label>邮箱:</label>
          <input
            type="email"
            name="email"
            value={formData.email}
            onChange={handleInputChange}
            className={errors.email ? 'error' : ''}
            placeholder="example@domain.com"
          />
          {errors.email && <span className="error-message">{errors.email}</span>}
        </div>

        <div className="form-group">
          <label>手机号:</label>
          <input
            type="tel"
            name="phone"
            value={formData.phone}
            onChange={handleInputChange}
            className={errors.phone ? 'error' : ''}
            placeholder="11位手机号"
          />
          {errors.phone && <span className="error-message">{errors.phone}</span>}
        </div>

        <div className="form-actions">
          <button type="submit" className="submit-btn">注册</button>
        </div>
      </form>
    </div>
  )
}

// 文件上传
function FileUploadExample() {
  const [files, setFiles] = useState([])
  const [dragOver, setDragOver] = useState(false)

  const handleFileSelect = (e) => {
    const selectedFiles = Array.from(e.target.files)
    setFiles(prev => [...prev, ...selectedFiles])
  }

  const handleDragOver = (e) => {
    e.preventDefault()
    setDragOver(true)
  }

  const handleDragLeave = (e) => {
    e.preventDefault()
    setDragOver(false)
  }

  const handleDrop = (e) => {
    e.preventDefault()
    setDragOver(false)
    
    const droppedFiles = Array.from(e.dataTransfer.files)
    setFiles(prev => [...prev, ...droppedFiles])
  }

  const removeFile = (index) => {
    setFiles(prev => prev.filter((_, i) => i !== index))
  }

  const clearFiles = () => {
    setFiles([])
  }

  return (
    <div className="example-container">
      <h4>文件上传</h4>
      
      <div 
        className={`upload-area ${dragOver ? 'drag-over' : ''}`}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
      >
        <div className="upload-icon">📁</div>
        <p>拖拽文件到这里或点击选择</p>
        <input
          type="file"
          multiple
          onChange={handleFileSelect}
          className="file-input"
        />
      </div>

      {files.length > 0 && (
        <div className="file-list">
          <div className="file-list-header">
            <h5>已选择的文件 ({files.length})</h5>
            <button onClick={clearFiles} className="clear-btn">清空</button>
          </div>
          
          {files.map((file, index) => (
            <div key={index} className="file-item">
              <div className="file-info">
                <span className="file-name">{file.name}</span>
                <span className="file-size">
                  {(file.size / 1024).toFixed(2)} KB
                </span>
              </div>
              <button 
                onClick={() => removeFile(index)}
                className="remove-file-btn"
              >
                删除
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

// 动态表单字段
function DynamicFormExample() {
  const [fields, setFields] = useState([
    { id: 1, name: '姓名', type: 'text', required: true },
    { id: 2, name: '邮箱', type: 'email', required: true },
    { id: 3, name: '年龄', type: 'number', required: false }
  ])

  const [formData, setFormData] = useState({})

  const addField = () => {
    const newField = {
      id: Date.now(),
      name: `字段${fields.length + 1}`,
      type: 'text',
      required: false
    }
    setFields([...fields, newField])
  }

  const removeField = (fieldId) => {
    setFields(fields.filter(field => field.id !== fieldId))
    
    // 同时删除对应的数据
    const newFormData = { ...formData }
    delete newFormData[fieldId]
    setFormData(newFormData)
  }

  const handleInputChange = (fieldId, value) => {
    setFormData(prev => ({
      ...prev,
      [fieldId]: value
    }))
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    
    const result = fields.map(field => ({
      fieldName: field.name,
      value: formData[field.id] || ''
    }))
    
    alert('动态表单数据:\n' + JSON.stringify(result, null, 2))
  }

  return (
    <div className="example-container">
      <h4>动态表单字段</h4>
      
      <div className="dynamic-form">
        <div className="field-config">
          <h5>字段配置</h5>
          {fields.map(field => (
            <div key={field.id} className="field-item">
              <input
                type="text"
                value={field.name}
                onChange={(e) => {
                  const newFields = fields.map(f =>
                    f.id === field.id ? { ...f, name: e.target.value } : f
                  )
                  setFields(newFields)
                }}
                className="field-name-input"
              />
              <select
                value={field.type}
                onChange={(e) => {
                  const newFields = fields.map(f =>
                    f.id === field.id ? { ...f, type: e.target.value } : f
                  )
                  setFields(newFields)
                }}
              >
                <option value="text">文本</option>
                <option value="email">邮箱</option>
                <option value="number">数字</option>
                <option value="textarea">文本域</option>
              </select>
              <label>
                <input
                  type="checkbox"
                  checked={field.required}
                  onChange={(e) => {
                    const newFields = fields.map(f =>
                      f.id === field.id ? { ...f, required: e.target.checked } : f
                    )
                    setFields(newFields)
                  }}
                />
                必填
              </label>
              <button 
                onClick={() => removeField(field.id)}
                className="remove-field-btn"
              >
                删除
              </button>
            </div>
          ))}
          
          <button onClick={addField} className="add-field-btn">
            添加字段
          </button>
        </div>

        <form onSubmit={handleSubmit} className="form">
          <h5>动态生成的表单</h5>
          {fields.map(field => (
            <div key={field.id} className="form-group">
              <label>
                {field.name}
                {field.required && <span className="required">*</span>}
              </label>
              
              {field.type === 'textarea' ? (
                <textarea
                  value={formData[field.id] || ''}
                  onChange={(e) => handleInputChange(field.id, e.target.value)}
                  required={field.required}
                />
              ) : (
                <input
                  type={field.type}
                  value={formData[field.id] || ''}
                  onChange={(e) => handleInputChange(field.id, e.target.value)}
                  required={field.required}
                />
              )}
            </div>
          ))}
          
          <div className="form-actions">
            <button type="submit" className="submit-btn">提交</button>
          </div>
        </form>
      </div>
    </div>
  )
}

function Forms() {
  return (
    <div className="example-page">
      <div className="example-header">
        <h1>表单处理</h1>
        <p>学习 React 中的表单处理，包括受控组件、验证和文件上传</p>
      </div>

      <div className="example-section">
        <h2>1. 基本受控组件</h2>
        <p>使用 useState 管理表单数据，实现受控组件：</p>
        
        <BasicControlledExample />
      </div>

      <div className="example-section">
        <h2>2. 文本域和下拉选择</h2>
        <p>处理不同类型的表单控件：</p>
        
        <TextareaSelectExample />
      </div>

      <div className="example-section">
        <h2>3. 表单验证</h2>
        <p>实现实时的表单验证和错误提示：</p>
        
        <ValidationExample />
      </div>

      <div className="example-section">
        <h2>4. 文件上传</h2>
        <p>处理文件选择和拖拽上传：</p>
        
        <FileUploadExample />
      </div>

      <div className="example-section">
        <h2>5. 动态表单字段</h2>
        <p>动态添加和删除表单字段：</p>
        
        <DynamicFormExample />
      </div>

      <div className="tip">
        <strong>表单处理最佳实践：</strong>
        <ul>
          <li>使用受控组件，让 React 成为数据的唯一来源</li>
          <li>为每个表单字段使用单独的 state 或使用对象管理</li>
          <li>实现实时验证，提供即时反馈</li>
          <li>使用适当的 input 类型（email、tel、number 等）</li>
          <li>为必填字段提供清晰的视觉指示</li>
          <li>处理表单重置和清除功能</li>
          <li>考虑使用表单库（如 Formik、React Hook Form）处理复杂表单</li>
          <li>对于大型表单，考虑字段验证和错误处理的抽象</li>
        </ul>
      </div>
    </div>
  )
}

export default Forms